#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include "log.h"
#include "util.h"
#include "cjson.h"

void* MALLOC(int size)
{
    void *ptr = malloc(size);
    if(ptr == NULL)
    {
        LOG(UTIL_LOG_MODULE, UTIL_LOG_PROC, "malloc error\n");
        exit(1);
    }
    return ptr;
}

void FREE(void *ptr)
{
    if(ptr != NULL)
    {
        free(ptr);
        ptr = NULL;
    }
}


char* ReturnStatus(char* status)
{
    char *out = NULL;
    cJSON *json = cJSON_CreateObject();
    if(NULL == json)
    {
        LOG(UTIL_LOG_MODULE, UTIL_LOG_PROC, "cJSON_CreateObject error\n");
        return NULL;
    }
    
    out = cJSON_Print(json);
    cJSON_AddStringToObject(json, "code", status);
    out = cJSON_Print(json);
    cJSON_Delete(json);
    return out;
}

int TrimSpace(char *inbuf)
{
    int ret = 0;
    if(NULL == inbuf)
    {
        return -1;
    }

    char *p = inbuf;
    int r = strlen(p) - 1;
    int l = 0;

    while(isspace(p[l]) && p[l] != '\0')
        l++;

    while(isspace(p[r]) && r > l)
        r--;

    int len = r - l + 1;
    strncpy(inbuf, p + l, len);
    inbuf[len] = '\0';

    return ret;
}

char* Memstr(char* fullData, int fullDataLen, char* substr)
{
    if(NULL == fullData || NULL == substr || fullDataLen <= 0)
    {
        return NULL;
    }

    if(strlen(substr) == 0)
    {
        return NULL;
    }

    int sublen = strlen(substr);
    char *cur = fullData;
    int strLen = fullDataLen - sublen + 1;
    for(int index = 0; index < strLen; index++)
    {
        if(*cur == *substr)
        {
            if(strncmp(cur, substr, sublen) == 0)
            {
                return cur;
            }
        }
        cur++;
    }

    return NULL;
}

int GetFileSuffix(char *filename, char *suffix)
{
    if(NULL == filename || NULL == suffix)
    {
        return -1;
    }

    char *p = strrchr(filename, '.');
    if(NULL == p)
    {
        return -1;
    }

    strncpy(suffix, p + 1, SUFFIX_LEN);
    return 0;
}